<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <link rel="stylesheet" href="/css/font-awesome-all.min.css">
    <style>
        .register-container {
            max-width: 1200px;
            margin: 50px auto;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        .form-section {
            margin-bottom: 30px;
            padding: 20px;
            border: 1px solid #eee;
            border-radius: 5px;
        }

        .form-row {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
        }

        .form-col {
            flex: 1;
            min-width: 300px;
        }

        @media (max-width: 768px) {
            .form-col {
                flex: 100%;
            }
        }
    </style>
</head>

<body>
    <div class="container register-container">
        <!-- 盐值解密区域 -->
        <div class="form-section">
            <h4>账户信息解密</h4>
            <div class="mb-3 d-flex align-items-end">
                <div class="flex-grow-1">
                    <label class="form-label">密码</label>
                    <input type="password" class="form-control" id="passwordInput" autocomplete placeholder="输入密码">
                </div>
                <div class="ms-3">
                    <button type="button" class="btn btn-secondary" onclick="decryptAccount()">获取账户信息</button>
                    <button type="button" class="btn btn-success ms-2" onclick="registerAll()"><i
                            class="fa-solid fa-registered"></i>注册所有</button>
                </div>
            </div>
        </div>

        <div class="form-row">
            <!-- 数据源注册表单 -->
            <!-- <div class="form-col form-section">
                <h4>数据源注册</h4>
                <form id="dsForm">
                    <button type="button" class="btn btn-primary mb-3" onclick="onClickRegisterDS()">注册数据源</button>
                    <div class="mb-3">
                        <label class="form-label">用户名</label>
                        <input type="text" class="form-control" name="userName" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">密码</label>
                        <input type="password" class="form-control" name="password" required>
                    </div>
                </form>
            </div> -->

            <!-- MQTT注册表单 -->
            <div class="form-col form-section">
                <h4>MQTT服务注册</h4>
                <form id="mqttForm">
                    <!-- <button type="button" class="btn btn-primary mb-3" ><i class="fa-solid fa-stop"></i></button> -->
                    <span class="status-button"><i class="fa-solid fa-stop"></i></span>
                    <div class="mb-3">
                        <label class="form-label">主机地址</label>
                        <input type="text" class="form-control" name="host" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">用户名</label>
                        <input type="text" class="form-control" name="userName" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">密码</label>
                        <input type="password" class="form-control" name="password" required>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 自定义确认对话框 -->
    <div class="modal fade" id="confirmModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog"
            style="position: fixed; top: 30%; left: 40%; transform: translate(-50%, -50%); margin: 0; min-width: 480px;">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">确认操作</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    确定要注册所有服务吗？
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="confirmYes">确定</button>
                </div>
            </div>
        </div>
    </div>
</body>
<script src="/js/jquery-3.7.1.js"></script>
<script src="/js/bootstrap.bundle.min.js"></script>
<script src="/js/font-awesome-all.min.js" data-auto-replace-svg="nest"></script>
<script src="/js/pub.js"></script>
<script src="/js/mqtt.js"></script>
<script>
    // 保存账号信息到本地存储
    function saveAccountToLocal(account) {
        localStorage.setItem('accountData', JSON.stringify(account));
        localStorage.setItem('lastUpdateTime', new Date().getTime());
    }

    // 从本地存储加载账号信息
    function loadAccountFromLocal() {
        const accountData = localStorage.getItem('accountData');
        if (accountData) {
            try {
                return JSON.parse(accountData);
            } catch (e) {
                console.error('解析本地存储数据失败:', e);
                return null;
            }
        }
        return null;
    }

    // 清除本地存储的账号信息
    function clearAccountFromLocal() {
        localStorage.removeItem('accountData');
        localStorage.removeItem('lastUpdateTime');
    }

    function decryptAccount() {
        const passwordStr = $('#passwordInput').val().trim();
        // 输入校验
        if (!passwordStr) {
            alert('请输入密码');
            $('#passwordInput').focus();
            return;
        }

        try {
            // 调用后端解密接口
            fetch('/sys-config/getAccount?password=' + passwordStr, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    "auth2045": getLoginToken()
                }
            })
                .then(response => response.json())
                .then(resp => {
                    if (resp && resp.flag == 1) {
                        let account = resp.data;
                        // 保存到本地存储
                        saveAccountToLocal(account);
                        // 填充表单
                        fillForms(account);
                    } else {
                        alert(resp.message || '解密失败');
                    }
                }).catch(error => {
                    console.error('请求错误:', error);
                    alert('请求出错，请稍后再试！');
                });
        } catch (e) {
            alert('解密失败: ' + e.message);
        }
    }

    // 填充表单数据
    function fillForms(account) {
        // 填充MQTT表单
        $('#mqttForm input[name="host"]').val(account.artermisHost || '');
        $('#mqttForm input[name="userName"]').val(account.artermisUser || '');
        $('#mqttForm input[name="password"]').val(account.artermisPassword || '');
    }

   

    function checkRegisterStatus() {

        fetch('/bean/getRegisterStatus', {
            method: 'GET',
            headers: {
                "auth2045": getLoginToken()
            }
        })
            .then(resp => resp.json())
            .then(data => {
                if (data.flag == 1) {
                    let status = data.data;
                    if (status.datasource === true) {
                        $('#dsForm button').prop('disabled', true).text('已注册');
                    }
                    else {
                        $('#dsForm button').prop('disabled', false).text('注册数据源');
                    }
                    if (status.artermis === true) {
                        $('#mqttForm .status-button').html('<i class="fa-solid fa-square-check" style="color:green;" ></i>');
                        setMqttStatus('true');
                    }
                    else {
                        $('#mqttForm .status-button').html('<i class="fa-solid fa-stop" style="color:red;" ></i>');
                    }
                }
            })
    }
   

    function registerAll() {

        // 检查MQTT表单必填字段
        const mqttHost = $('#mqttForm input[name="host"]').val().trim();
        const mqttUser = $('#mqttForm input[name="userName"]').val().trim();
        const mqttPassword = $('#mqttForm input[name="password"]').val().trim();
        if (!mqttHost || !mqttUser || !mqttPassword) {
            alert('MQTT主机地址、用户名和密码不能为空');
            if (!mqttHost) $('#mqttForm input[name="host"]').focus();
            else if (!mqttUser) $('#mqttForm input[name="userName"]').focus();
            else $('#mqttForm input[name="password"]').focus();
            return;
        }

        // 显示自定义确认对话框
        const confirmModal = new bootstrap.Modal('#confirmModal');
        confirmModal.show();

        // 一次性事件绑定
        $('#confirmYes').off('click').on('click', function () {
            confirmModal.hide();

            // 禁用按钮防止重复点击
            $('button').prop('disabled', true);            
            $('.btn-success').text('注册中...');
             
            registerMQTT(function () {
                // 全部完成后恢复按钮状态
                checkRegisterStatus();
                $('button').prop('disabled', false);
                $('.btn-success').text('注册所有');
                setMqttStatus('true');
            });
        });
        return;
    }

    

    function registerMQTT(callback) {
        const formData = $('#mqttForm').serialize();

        fetch('/bean/register-mqtt',
            {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                    "auth2045": getLoginToken()
                },
                body: formData
            }
        )
            .then(resp => resp.json())
            .then(data => {
                checkRegisterStatus();
                if (typeof callback === 'function') callback();
            }
            )
            .catch(() => {
                alert('MQTT注册失败');
                $('button').prop('disabled', false);
                checkRegisterStatus();
            }

            );

    }

     $(document).ready(function () {
        // 初始化检查注册状态
        checkRegisterStatus();

        // 尝试从本地存储加载账号信息
        const savedAccount = loadAccountFromLocal();
        if (savedAccount) {
            fillForms(savedAccount);
            $('#passwordInput').val('******'); // 密码不保存，显示占位符
        }
        //设置检查注册状态的间隔时间，每隔1000毫秒检查一次
        window.registerInterval = setInterval(checkRegisterStatus, 1000);
    });

     

    window.addEventListener("unload", function (event) {
        if (window.registerInterval) {
            clearInterval(window.registerInterval);
            delete window.registerInterval;
        }
    });
</script>

</html>